import { defineStore } from 'pinia';
import { ref, reactive } from 'vue';
import { Message } from '@arco-design/web-vue';
import customerApi from '@/api/customer';

export const useCustomerStore = defineStore('customer', () => {
  // 状态
  const loading = ref(false);
  const customers = ref([]);
  const customerDetail = ref(null);
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const dropdownLoading = ref(false);
  const customerDropdownList = ref([]);

  /**
   * 获取客户列表
   * @param {Object} params - 查询参数
   * @param {Boolean} showLoading - 是否显示加载状态，默认为true
   * @param {Boolean} showSuccessMsg - 是否显示成功消息，默认为false
   * @returns {Promise} 请求结果
   */
  async function getCustomerList(params = {}, showLoading = true, showSuccessMsg = false) {
    if (showLoading) loading.value = true;
    
    try {
      const queryParams = {
        page: pagination.current,
        page_size: pagination.pageSize,
        ...params
      };
      
      const response = await customerApi.getCustomerList(queryParams);
      
      if (response.code === 0) {
        customers.value = response.data.list || [];
        pagination.total = response.data.total || 0;
        
        // 显示成功消息
        if (showSuccessMsg) {
          Message.success(`成功获取客户列表，共${customers.value.length}条记录`);
        }
        
        return { success: true, data: {
          list: customers.value,
          pagination: {
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total
          }
        }};
      }
      
      Message.error(response.message || '获取客户列表失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('获取客户列表出错:', error);
      Message.error('获取客户列表失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      if (showLoading) loading.value = false;
    }
  }

  /**
   * 获取客户详情
   * @param {Number} id - 客户ID
   * @returns {Promise} 请求结果
   */
  async function getCustomerDetail(id) {
    loading.value = true;
    try {
      const response = await customerApi.getCustomerDetail(id);
      
      if (response.code === 0) {
        customerDetail.value = response.data;
        return { success: true, data: customerDetail.value };
      }
      
      Message.error(response.message || '获取客户详情失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('获取客户详情出错:', error);
      Message.error('获取客户详情失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 创建客户
   * @param {Object} data - 客户数据
   * @returns {Promise} 请求结果
   */
  async function createCustomer(data) {
    loading.value = true;
    try {
      const response = await customerApi.createCustomer(data);
      
      if (response.code === 0) {
        Message.success('创建客户成功');
        return { success: true };
      }
      
      Message.error(response.message || '创建客户失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('创建客户出错:', error);
      Message.error('创建客户失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 更新客户
   * @param {Number} id - 客户ID
   * @param {Object} data - 客户数据
   * @returns {Promise} 请求结果
   */
  async function updateCustomer(id, data) {
    loading.value = true;
    try {
      const response = await customerApi.updateCustomer(id, data);
      
      if (response.code === 0) {
        Message.success('更新客户成功');
        return { success: true };
      }
      
      Message.error(response.message || '更新客户失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('更新客户出错:', error);
      Message.error('更新客户失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 删除客户
   * @param {Number} id - 客户ID
   * @returns {Promise} 请求结果
   */
  async function deleteCustomer(id) {
    loading.value = true;
    try {
      const response = await customerApi.deleteCustomer(id);
      
      if (response.code === 0) {
        Message.success('删除客户成功');
        return { success: true };
      }
      
      Message.error(response.message || '删除客户失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('删除客户出错:', error);
      Message.error('删除客户失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 批量删除客户
   * @param {Array} ids - 客户ID数组
   * @returns {Promise} 请求结果
   */
  async function batchDeleteCustomers(ids) {
    loading.value = true;
    try {
      const response = await customerApi.batchDeleteCustomers(ids);
      
      if (response.code === 0) {
        Message.success('批量删除客户成功');
        return { success: true };
      }
      
      Message.error(response.message || '批量删除客户失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('批量删除客户出错:', error);
      Message.error('批量删除客户失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 导入客户数据
   * @param {FormData} formData - 包含客户数据的表单
   * @returns {Promise} 请求结果
   */
  async function importCustomers(formData) {
    loading.value = true;
    try {
      const response = await customerApi.importCustomers(formData);
      
      if (response.code === 0) {
        Message.success('导入客户数据成功');
        return { success: true, data: response.data };
      }
      
      Message.error(response.message || '导入客户数据失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('导入客户数据出错:', error);
      Message.error('导入客户数据失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 导出客户数据
   * @param {Object} params - 导出参数
   * @returns {Promise} 请求结果
   */
  async function exportCustomers(params = {}) {
    loading.value = true;
    try {
      const response = await customerApi.exportCustomers(params);
      
      // 处理文件下载
      const blob = new Blob([response], { type: 'application/vnd.ms-excel' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = '客户数据.xlsx';
      link.click();
      URL.revokeObjectURL(link.href);
      
      Message.success('导出客户数据成功');
      return { success: true };
    } catch (error) {
      console.error('导出客户数据出错:', error);
      Message.error('导出客户数据失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 设置分页
   * @param {Number} page - 页码
   * @param {Number} pageSize - 每页数量
   */
  function setPagination(page, pageSize) {
    pagination.current = page;
    if (pageSize) pagination.pageSize = pageSize;
  }

  /**
   * 获取所有客户（用于下拉选择）
   * @returns {Promise} 请求结果
   */
  async function getAllCustomers() {
    try {
      const response = await customerApi.getCustomerList({ page_size: 9999 });
      
      if (response.code === 0) {
        return { success: true, data: response.data.list || [] };
      }
      
      return { success: false, message: response.message, data: [] };
    } catch (error) {
      console.error('获取所有客户出错:', error);
      return { success: false, message: error.message || '未知错误', data: [] };
    }
  }

  /**
   * 获取所有客户用于下拉选择
   * @returns {Promise<boolean>} - 是否成功
   */
  async function fetchCustomerDropdownList() {
    dropdownLoading.value = true;
    try {
      const response = await customerApi.getCustomerList({ page: 1, page_size: 999 });
      if (response.code === 0) {
        customerDropdownList.value = response.data.list || [];
        return true;
      } else {
        Message.error(response.message || '获取客户下拉列表失败');
        customerDropdownList.value = [];
        return false;
      }
    } catch (error) {
      console.error('获取客户下拉列表出错:', error);
      Message.error('获取客户下拉列表失败: ' + (error.message || '未知错误'));
      customerDropdownList.value = [];
      return false;
    } finally {
      dropdownLoading.value = false;
    }
  }

  return {
    loading,
    customers,
    customerDetail,
    pagination,
    dropdownLoading,
    customerDropdownList,
    getCustomerList,
    getCustomerDetail,
    createCustomer,
    updateCustomer,
    deleteCustomer,
    batchDeleteCustomers,
    importCustomers,
    exportCustomers,
    setPagination,
    getAllCustomers,
    fetchCustomerDropdownList
  };
}); 